import { CameraRoll, PermissionsAndroid, NativeModules, Platform } from 'react-native'
import * as WeChat from "react-native-wechat"
import { Jx, Jpp } from "./Jx"
import { Build } from './Build'
import { Dialog } from "./Dialog"


// import { cQQios as uQQ } from "./QQ.ios"
// export { uQQ }
export const uQQ = Platform.select({
    ios: () => require("./QQ.ios").cQQios,
    android: () => require("./QQ.android").cQQandroid,
})();

export class cSys{  

    static toImageFile(uri){
        return (uri.toLowerCase().includes('file://')) ? uri: ('file://' + uri);
    }
    static toImageFileless(uri){
        return (uri.toLowerCase().includes('file://')) ? uri.substr(7) : uri;
    }

    // 请求权限（相机/相册）
    static _isReadExternalSorageAndCamera = false;
    static promiseCapturePermission(toast){
        if(Jpp.isIOS || this._isReadExternalSorageAndCamera){
            return Promise.resolve(true);
        }
        return new Promise(resolve=>{
            PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE).then(granted=>{
                if(granted == PermissionsAndroid.RESULTS.GRANTED){
                    PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.CAMERA).then(granted2=>{
                        if(granted2 == PermissionsAndroid.RESULTS.GRANTED){
                            this._isReadExternalSorageAndCamera = true;
                            resolve && resolve(true);
                        }else{
                            console.warn(Jx.stringify(err));
                            resolve && resolve(false);
                        }
                    })
                    .catch(err=>{
                        console.warn(Jx.stringify(err));
                        resolve && resolve(false);
                    })
                }else{
                    console.warn(Jx.stringify(err));
                    resolve && resolve(false);
                }
            })
            .catch(err=>{
                console.warn(Jx.stringify(err));
                resolve && resolve(false);
            })
        });
    }

    // 保存图片到相册
    static toCameraRoll(image, toast){
        if(!toast){
            return CameraRoll.saveToCameraRoll(image);
        }
        CameraRoll.saveToCameraRoll(image)
        .then(r=>{
            console.warn(Jx.stringify(r));
            Dialog.toast("图片已保存");
        })
        .catch(e=>{
            console.warn(Jx.stringify(e));
            Dialog.toast("保存失败");
        });
    }

    // 判断微信是否注册API
    static registerWeChat(appid){
        if(this.isWechatInstalled()){
            return Promise.resolve(true);
        }
        return new Promise(resolve=>{
            WeChat.registerApp(appid).then(r=>{
                console.log("微信注册then: ", JSON.stringify(r));
                this.checkWechatInstalled();
                resolve(true);
            }).catch(err=>{
                console.warn("微信注册error: ", JSON.stringify(err));
                resolve(false);
            });
        });
    }

    static _isWechatInstalled = false;
    // 判断微信是否安装
    static checkWechatInstalled(){
        if(this._isWechatInstalled){
            return Promise.resolve(true);
        }
        console.log("检测微信是否安装");
        return new Promise(resolve=>{
            WeChat.isWXAppInstalled()
            .then(isInstalled=>{
                if(isInstalled){
                    console.log("微信已安装");
                    this._isWechatInstalled = true;
                    resolve && resolve(true);
                }else{
                    console.warn("微信未安装");
                    resolve && resolve(false);
                }
            })
            .catch(err=>{
                console.warn(Jx.stringify(err));
                resolve && resolve(false);
            })
        })
    }
    static isWechatInstalled(toast){
        if(this._isWechatInstalled){
            return true;
        }
        if(toast){
            Dialog.toast("未安装微信");
        }
        return false;
    }

    static _isQQInstalled = false;
    // 判断QQ是否安装
    static checkQQInstalled(){
        if(this._isQQInstalled){
            return true;
        }
        console.log("检测QQ是否安装");
        uQQ.check().then(r=>{
            console.log('QQ已安装');
            this._isQQInstalled = true;
        }).catch(err=>{
            if(err){
                console.warn("QQ检测错误");
            }else{
                console.warn("QQ未安装"); 
            }
        });
    }
    static isQQInstalled(toast){
        if(this._isQQInstalled){
            return true;
        }
        if(toast){
            Dialog.toast("未安装QQ");
        }
        return false;
    }
    
    // static promiseCapturePermission(toast){
    //     return new Promise(resolve=>{
    //         PermissionsAndroid.requestMultiple([
    //             PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, 
    //             PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, 
    //             PermissionsAndroid.PERMISSIONS.CAMERA
    //         ]).then(granteds=>{
    //             if(!granteds || 
    //                 granteds[0] != PermissionsAndroid.RESULTS.GRANTED || 
    //                 granteds[1] != PermissionsAndroid.RESULTS.GRANTED ||
    //                 granteds[2] != PermissionsAndroid.RESULTS.GRANTED){
    //                 if(toast){
    //                     Dialog.toast("无权限访问相册");
    //                 }
    //                 resolve && resolve(false);
    //                 return;
    //             }
    //             this._isReadExternalSorageAndCamera = true;
    //             resolve && resolve(true);
    //         })
    //         .catch(err=>{
    //             console.warn(Jx.stringify(err));
    //             resolve && resolve(false);
    //         })
    //     })
    // }
    // 微信授权登录
    static _isJumping2Wechat = false;  
    static wchatAuthorize(resolve, reject){
        this._isJumping2Wechat = true;
        // snsapi_base
        // snsapi_userinfo
        // 正式 1f83b434a0a0250bd012c399d56eafb3
        // 调试 d7521bae7b7463d2dcf311173589303f
        WeChat.sendAuthRequest("snsapi_userinfo", "ax123451")
        .then(res=>{
            this._isJumping2Wechat = false;
            console.log("微信token: ", Jx.stringify(res));
            switch(parseInt(res.errCode)) {
                case 0:
                    // 验证此次操作是用户自己进行的，否则结束操作
                    if (res.state != "ax123451") {
                        Dialog.toast("操作错误")
                        reject(res);
                        break;
                    }
                    Dialog.retain(true);
                    console.log("微信errCode0: ", res.code);
                    fetch("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+
                        Build.appid + "&secret=" + Build.secret + "&code="+ res.code + 
                        "&grant_type=authorization_code")
                    .then(r=>r.json())
                    .then(r=>{
                        console.log(Jx.stringify(r));
                        fetch("https://api.weixin.qq.com/sns/userinfo?access_token="+
                            r.access_token +'&openid=' + r.openid)
                        .then(r=>r.json())
                        .then(r=>{
                            Dialog.release();
                            console.log(Jx.stringify(r));
                            resolve(r);
                        })
                    })
                    .catch(err=>{
                        Dialog.release();
                        console.warn(Jx.stringify(err));
                        reject(err);
                    })
                // //   验证此次操作是用户自己进行的，否则结束操作
                //   if (res.state != __conf__.state) {
                //     toastModule.run('这里state不正确');
                //     return;
                //   }
                // //   请求后端，登录操作
                //   http.get(__conf__.url + '&code=' + res.code, (d) => {
                //     __conf__.callback(d); // 运行回调函数
                //   });
                    break;
                case -4:
                    console.warn("用户拒绝");
                    reject(res);
                    break;
                case -2:
                    console.warn("用户取消");
                    reject(res);
                    break; 
                default:
                    console.warn("微信errCode其他: ", Jx.stringify(res));
                    reject(res);
                    break;
                }
        })
        .catch(err=>{
            console.warn("微信error: ", Jx.stringify(err));
            this._isJumping2Wechat = false;
            reject(err);
        })
    }

    static _timeout = null;
    static fetWchatRelease(){
        if(this._timeout){
            clearTimeout(this._timeout);
        }
        this._timeout = setTimeout(()=>{
            if(this._isJumping2Wechat){
                this._isJumping2Wechat = false;
                Dialog.release();
            }
        }, 5000);
        Dialog.retain(true);
        console.log("跳转微信授权登录: ");
        return new Promise((resolve, reject)=>{
            this.wchatAuthorize(resolve, reject);
        });
    }
}